標準正規密度の面積

標準正規密度の塗りつぶしグラフを描く関数
x1, x2 : 下側?上側パーセンタイル
xmin, xmax : グラフを描く範囲の最小値?最大値(標準では-3から3の範囲)

normd <- function(x1, x2, xmin = -3, xmax = 3) {
    if (x1 <= xmin) 
        z1 <- xmin else z1 <- x1
    if (x2 >= xmax) 
        z2 <- xmax else z2 <- x2
    x <- seq(xmin, xmax, 0.01)
    plot(x, dnorm(x, mean = 0, sd = 1), type = "n")
    xaxis <- seq(z1, z2, length = 100)
    yaxis <- c(0, dnorm(xaxis, mean = 0, sd = 1), 0)
    xaxis <- c(z1, xaxis, z2)
    polygon(xaxis, yaxis, density = 25, col = "red")
    curve(dnorm(x, mean = 0, sd = 1), type = "l", add = T)
    ypos <- dnorm(z1, mean = 0, sd = 1)
    title(main = paste(round(pnorm(x2) - pnorm(x1), digits = 4)))
}

(例) X ~ N(0,1)

normd(-Inf, 1.96)  # P(X≦1.96)

plot of chunk unnamed-chunk-2

normd(1, 2)  # P(1≦X≦2)

plot of chunk unnamed-chunk-2

normd(1.96, Inf)  # P(X≧1.96)

plot of chunk unnamed-chunk-2